<template>
  <div class="app-container">
    <div v-loading="loading" class="head-container">
      <label class="el-form-item-label">员工编码</label>
      <el-input v-model="user.username" clearable placeholder="员工编码" style="width: 185px;" class="filter-item" readonly />
      <label class="el-form-item-label">工位编码</label>
      <el-input v-model="scanForm.stationId" clearable placeholder="工位编码" style="width: 185px;" class="filter-item" readonly />

      <label class="el-form-item-label">批次号</label>
      <el-input
        ref="processRef"
        v-model.trim="scanForm.processcardCode"
        clearable
        placeholder="批次号"
        style="width: 185px;"
        class="filter-item"
        @keyup.enter.native="bindingProcesscard"
      />

      <label class="el-form-item-label">容器编码</label>
      <el-input
        ref="containerRef"
        v-model.trim="scanForm.palletCode"
        maxlength="4"
        clearable
        placeholder="容器编码"
        style="width: 185px;"
        class="filter-item"
        @keyup.enter.native="bindingPallet"
      />
      <!-- bindingPalletConfirmation = true -->
      <el-button
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-refresh-left"
        @click="reset()"
      >重置</el-button>
      <div>
        <label class="el-form-item-label" style="font-size: 22px;padding-top: 8px;">选择流向</label>
        <el-select v-model="scanForm.flowTo" clearable placeholder="请选择">
          <el-option
            v-for="item in flowMission"
            :key="item.id"
            :label="item.name"
            :value="item.flowTo"
          />
        </el-select>
        <label class="el-form-item-label" style="font-size: 22px;padding-top: 8px;">作业载盘</label>
        <el-input v-model="scanForm.workPalletCode" readonly clearable placeholder="作业载盘" style="width: 185px;" />
        <el-radio v-model="scanForm.temp" class="filter-item" style="margin-top: 5px;margin: 0 10px;" :label="1">有料温线</el-radio>
        <el-radio v-model="scanForm.temp" class="filter-item" style="margin-top: 5px;" :label="0">无料温线</el-radio>
      </div>
      <el-dialog title="载盘绑定" :visible.sync="bindingPalletConfirmation" width="50%" :before-close="handleClose">
        <span style="font-size: 45px;font-weight: bold;color: black;">当前载盘号为：{{ scanForm.palletCode }}，是否绑定？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="bindingPalletConfirmation = false">取 消</el-button>
          <el-button type="primary" @click="bindingPallet">确 定</el-button>
        </span>
      </el-dialog>

      <!-- <el-card style="margin-top: 30px;">

      </el-card> -->

      <el-card style="margin-top: 30px;">
        <el-descriptions
          title="批次信息"
          size="medium"
          :content-style="{ 'font-size': '32px' }"
          :label-style="{ 'font-size': '32px' }"
        >
          <el-descriptions-item label="批次号ID">{{ addForm.id }}</el-descriptions-item>
          <el-descriptions-item label="批次号">{{ scanProcesscardCode }}</el-descriptions-item>
          <el-descriptions-item label="工程号">{{ addForm.workNum }}</el-descriptions-item>
          <el-descriptions-item label="产品类型">{{ addForm.productType }}</el-descriptions-item>
          <el-descriptions-item label="板件长">{{ addForm.size1 }}</el-descriptions-item>
          <el-descriptions-item label="板件宽">{{ addForm.size2 }}</el-descriptions-item>
          <el-descriptions-item label="厚度">{{ addForm.thick }}</el-descriptions-item>
          <el-descriptions-item label="材质">{{ addForm.material }}</el-descriptions-item>
          <el-descriptions-item label="压合配方">{{ addForm.layerName }}</el-descriptions-item>
          <el-descriptions-item label="外层板数量">{{ addForm.qty }}</el-descriptions-item>
          <!-- <el-descriptions-item label="底板尺寸">{{ addForm.consumeRate }}</el-descriptions-item> -->

        </el-descriptions>
        <div class="rightbutton">
          <el-button type="primary" size="medium" @click="openNewPage">打开叠法图窗口</el-button>
          <el-button type="warning" size="medium" @click="shutdownLayUp">结束生产</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { bindingWorkStation, bindingPallet, shutdownLayUp, getFlowTo, getPicture } from '@/api/workStation'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      scanProcesscardCode: '',
      loading: false,
      bindingPalletConfirmation: false,
      codeImg: {},
      items: [
        { type: 'danger', label: 'OFF' },
        { type: 'success', label: 'ON' },
        { type: 'success', label: 'ON' },
        { type: 'danger', label: 'OFF' }
      ],
      leftformLabelWidth: '100px',
      rightformLabelWidth: '80px',
      addForm: {},
      scanForm: {
        processcardCode: '',
        stationId: '',
        palletCode: '',
        flowTo: 1,
        kuruma: '',
        qty: '',
        workPalletCode: '',
        temp: 0
      },
      formRules: {},
      timer: null,
      lastTime: '',
      nextTime: '',
      lastCode: '',
      nextCode: '',
      flowMission: [],
      btn: {
        takeOff: false
      },
      gelInfoList: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.scanForm.workPalletCode = this.$route.query.palletCode
    this.getFlowTo()
    if (localStorage.getItem('processcardCode')) {
      this.scanForm.processcardCode = localStorage.getItem('processcardCode')
      this.bindingProcesscard()
    }
  },
  mounted() {
    const localStationCode = sessionStorage.getItem('hiddenStationCode')
    this.scanForm.stationId = this.$route.query.stationCode || localStationCode
    if (this.scanForm.stationId === null || this.scanForm.stationId === undefined) {
      this.$router.push('/laminationManagement/inputWorkStation')
      return
    }
    this.$refs.processRef.focus()
    this.timer = setInterval(() => {
      if (this.scanForm.processcardCode === '') {
        this.$refs.processRef.focus()
      } else if (this.scanForm.palletCode === '' && this.scanForm.processcardCode !== '') {
        this.$refs.containerRef.focus()
      }
    }, 2000)
    window.document.onkeypress = (e) => {
      if (window.event) {
        // IE
        this.nextCode = e.keyCode
      } else if (e.which) {
        // Netscape/Firefox/Opera
        this.nextCode = e.which
      }
      if (e.which === 13) {
        // 键盘回车事件
        if (this.scanForm.palletCode.length < 3) return // 扫码枪的速度很快，手动输入的时间不会让code的长度大于2，所以这里不会对扫码枪有效
        this.lastCode = ''
        this.lastTime = ''
        return
      }
      this.nextTime = new Date().getTime()
      if (!this.lastTime && !this.lastCode) {
        this.scanForm.palletCode = '' // 清空上次的条形码
      }
      this.lastCode = this.nextCode
      this.lastTime = this.nextTime
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    sessionStorage.removeItem('hiddenStationCode')
  },
  methods: {
    judgeIsComment() {
      if (this.scanForm.flowTo === '1') {
        this.$confirm('此操作开启后，载盘将进入立库, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.scanForm.flowTo = '1'
          window.localStorage.setItem('flowTo', this.scanForm.flowTo)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }).catch(() => {
          this.scanForm.flowTo = '2'
          window.localStorage.setItem('flowTo', this.scanForm.flowTo)
          this.$message({
            type: 'info',
            message: '取消操作'
          })
        })
      } else {
        this.$confirm('此操作关闭后, 载盘将不进入立库，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.scanForm.flowTo = '2'
          window.localStorage.setItem('flowTo', this.scanForm.flowTo)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }).catch(() => {
          this.scanForm.flowTo = '1'
          window.localStorage.setItem('flowTo', this.scanForm.flowTo)
          this.$message({
            type: 'info',
            message: '取消操作'
          })
        })
      }
    },
    handleClose() {
      this.bindingPalletConfirmation = false
    },
    getFlowTo() {
      getFlowTo().then(res => {
        this.flowMission = res.data.flowMission
      })
    },
    shutdownLayUp() {
      shutdownLayUp(this.scanForm.palletCode).then(res => {
        if (res.meta.code === 200) {
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    // 绑定工艺卡
    // processcardCode 批次号
    // stationId 工位编码
    bindingProcesscard() {
      if (this.scanForm.processcardCode !== '' && this.scanForm.stationId !== '') {
        this.loading = true
        bindingWorkStation(this.scanForm.processcardCode, this.scanForm.stationId).then(res => {
          if (res.meta.code === 200) {
            this.scanProcesscardCode = this.scanForm.processcardCode
            this.loading = false
            this.$refs.containerRef.focus()
            this.addForm = res.data.mesMessage.processcard
            getPicture(this.addForm.workNum).then(res => {
              this.codeImg = window.URL.createObjectURL(res)
              console.log(this.codeImg)
              window.localStorage.setItem('image', this.codeImg)
              window.localStorage.setItem('processcardCode', this.scanForm.processcardCode)
            })
          } else {
            this.loading = false
            this.$confirm(res.meta.msg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              showCancelButton: false,
              center: true
            })
            // this.$message.error(res.meta.msg)
            this.scanForm.processcardCode = ''
          }
        })
      } else {
        if (this.scanForm.processcardCode === '' && this.scanForm.stationId !== '') {
          this.$message.warning('批次号为空，请重新输入')
        } else if (this.scanForm.processcardCode !== '' && this.scanForm.stationId === '') {
          this.$message.warning('工位编码为空，请重新输入')
        } else {
          this.$message.warning('工位编码、批次号为空，请重新输入')
        }
      }
    },
    // 绑定载盘
    // palletCode 容器编码
    // stationId 工位编码
    bindingPallet() {
      if (this.scanForm.palletCode !== '' && this.scanForm.stationId !== '') {
        if (this.scanForm.palletCode.toString().length === 4) {
          bindingPallet(this.scanForm.palletCode, this.scanForm.stationId, this.scanForm.flowTo, this.scanForm.temp).then(res => {
            if (res.meta.code === 200) {
              this.scanForm.temp = 0
              this.bindingPalletConfirmation = false
              this.$message.success({
                message: res.meta.msg,
                center: true,
                duration: 8000,
                customClass: 'custom-message'
              })
              this.scanForm.workPalletCode = this.scanForm.palletCode
              this.scanForm.palletCode = ''
            } else {
              this.$message.error(res.meta.msg)
              this.scanForm.palletCode = ''
            }
          })
        } else {
          this.$message.warning({
            message: '请扫描4位正确的载盘号',
            center: true,
            duration: 8000
          })
          this.scanForm.palletCode = ''
        }
      } else {
        if (this.scanForm.palletCode === '' && this.scanForm.stationId !== '') {
          this.$message.warning('容器编码为空，请重新输入')
        } else if (this.scanForm.palletCode !== '' && this.scanForm.stationId === '') {
          this.$message.warning('工位编码为空，请重新输入')
        } else {
          this.$message.warning('容器编码、批次号为空，请重新输入')
        }
      }
    },
    // base64转png
    base64ImgtoFile(dataurl, filename = 'file') {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    // 打开叠法图
    openNewPage() {
      const { href } = this.$router.resolve({
        path: `/laminationManagement/Superimposed`,
        query: {
          processcardCode: this.scanProcesscardCode,
          workNum: this.addForm.workNum
        }
      })
      window.open(href, '_blank')
    },

    reset() {
      this.scanForm.processcardCode = ''
      this.scanForm.palletCode = ''
      this.$refs.processRef.focus()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-descriptions--medium:not(.is-bordered) .el-descriptions-item__cell {
  padding-bottom: 36px;
}

::v-deep .custom-message {
  font-size: 180px;
  /* 修改为你想要的字体大小 */
}

::v-deep .el-descriptions__title {
  font-size: 36px;
}
</style>
